<template>
  <common-list>
    <template v-if="TraceabilityHistoryDiv">
      <traceability-history
          @changeTraceabilityHistoryDiv="changeTraceabilityHistoryDiv"
          :name="historyData"
          :formData="formData"
      />
    </template>
    <template v-else>
      <common-search slot="search" @search="handleQuery" @reset="resetQuery">
        <el-form
            :model="queryParams"
            ref="queryForm"
            :inline="true"
            @submit.native.prevent
            v-show="showSearch"
            label-width="89px"
        >
          <el-form-item label="敏感字段类型" prop="workId">
            <el-select
                clearable
                v-model="queryParams.workId"
                @change="queryParamsChange(queryParams.workId)"
            >
              <el-option label="全部" :value="null"></el-option>
              <el-option
                  v-for="(item, index) in senstiveTypeArr"
                  :label="item.name"
                  :key="index"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="敏感字段" prop="sensitiveName">
            <el-select clearable v-model="queryParams.sensitiveName">
              <el-option label="全部" :value="null"></el-option>
              <el-option
                  v-for="(item, index) in senstiveNameArr"
                  :label="item"
                  :key="index"
                  :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="任务名称" prop="jobName">
            <common-input
                v-model="queryParams.jobName"
                clearable
                @enter="handleQuery"
                placeholder="请输入"
            />
          </el-form-item>
          <!--          <el-form-item label="应用" prop="6">-->
          <!--            <el-select clearable v-model="queryParams.applicationId">-->
          <!--              <el-option label="全部" :value="null"></el-option>-->
          <!--              <el-option-->
          <!--                v-for="(item, index) in applicationNameArr"-->
          <!--                :label="item.name"-->
          <!--                :key="index"-->
          <!--                :value="item.value"-->
          <!--              />-->
          <!--            </el-select>-->
          <!--          </el-form-item>-->
          <el-form-item label="状态" prop="status">
            <el-select clearable v-model="queryParams.status">
              <el-option label="全部" :value="null"></el-option>
              <el-option label="启用" :value="0"/>
              <el-option label="停用" :value="1"/>
            </el-select>
          </el-form-item>
        </el-form>
      </common-search>

      <el-row :gutter="10" class="mb8" slot="tools">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd"
          >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              :disabled="!showBatch"
              @click="handleDelete"
          >批量删除
          </el-button>
        </el-col>
      </el-row>

      <common-table
          slot="content"
          v-loading="loading"
          :data="list"
          @selection-change="handleSelectionChange"
      >
        <el-table-column
            type="selection"
            width="55"
            align="center"
            @change="handleSelectionChange"
        />
        <el-table-column label="任务名称" align="left" prop="jobName"/>
        <el-table-column label="执行周期" align="left" prop="cronExpression">
        </el-table-column>
        <!--        <el-table-column label="应用" align="left" prop="applicationName">-->
        <!--        </el-table-column>-->
        <el-table-column label="协议" align="left" prop="protocolName">
        </el-table-column>
        <el-table-column
            label="敏感字段类型"
            align="left"
            prop="workName"
            show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column label="敏感字段" align="left" prop="sensitiveName">
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status === '0'" type="success">启用</el-tag>
            <el-tag v-if="scope.row.status === '1'" type="danger">停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column
            label="操作"
            align="left"
            class-name="small-padding fixed-width"
            width="200"
        >
          <template slot-scope="scope">
            <el-button
                type="text"
                @click="immediateExecuteTask(scope.row)"
                v-if="scope.row.status === '0'"
            >立即执行
            </el-button>

            <el-button type="text" @click="taskHistoryFn(scope.row)">执行历史</el-button>

            <el-dropdown @command="handleCommand" trigger="click">
              <span
                  class="el-dropdown-link"
                  style="
                  cursor: pointer;
                  color: #409eff;
                  margin-left: 10px;
                  font-size: 12px;
                "
              >
                更多<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="setCommand('edit', scope.row, 1)">
                  <span style="font-size: 12px !important"> 编辑 </span>
                </el-dropdown-item>
                <el-dropdown-item :command="setCommand('change', scope.row)">
                  <span style="font-size: 12px !important">
                    {{ scope.row.status === '0' ? '停用' : '启用' }}
                  </span>
                </el-dropdown-item>
                <el-dropdown-item :command="setCommand('delete', scope.row)">
                  <span style="font-size: 12px !important"> 删除 </span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </common-table>

      <pagination
          slot="pagination"
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
      />

      <!-- 添加或编辑执行策略管理对话框 -->
      <common-edit-dialog
          :title="title"
          :button-loading="loading"
          :visible.sync="open"
          @cancel="cancel"
          @submit="submitForm"
          :buttonLoading="buttonLoading"
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="任务名称" prop="jobName">
                <common-input
                    v-model="form.jobName"
                    clearable
                    placeholder="请输入"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="执行周期" prop="cronExpression">
                <common-input
                    :verify="false"
                    v-model="form.cronExpression"
                    placeholder="请输入"
                />
              </el-form-item>
            </el-col>
            <!--            <el-col :span="12">-->
            <!--              <el-form-item label="应用" prop="applicationId">-->
            <!--                <el-select clearable v-model="form.applicationId">-->
            <!--                  <el-option-->
            <!--                    v-for="(item, index) in applicationNameArr"-->
            <!--                    :label="item.name"-->
            <!--                    :key="index"-->
            <!--                    :value="item.value"-->
            <!--                  />-->
            <!--                </el-select>-->
            <!--              </el-form-item>-->
            <!--            </el-col>-->
            <el-col :span="12">
              <el-form-item label="协议" prop="protocolName">
                <el-select clearable v-model="form.protocolName">
                  <el-option label="http" value="http"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="敏感字段类型" prop="workId">
                <el-select
                    v-model="form.workId"
                    clearable
                    @change="workIdChange(form.workId)"
                >
                  <el-option
                      v-for="(item, index) in senstiveTypeArr"
                      :label="item.name"
                      :key="index"
                      :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="敏感字段" prop="sensitiveName">
                <el-select
                    v-model="form.sensitiveName"
                    clearable
                    filterable
                    allow-create
                    default-first-option
                >
                  <el-option
                      v-for="(item, index) in senstiveNameArr"
                      :label="item"
                      :key="index"
                      :value="item"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </common-edit-dialog>
    </template>
  </common-list>
</template>

<script>
import {
  traceJobAdd,
  applicationNameList,
  changeStatus,
  traceJobList,
  traceJobRemove,
  senstiveTypeList,
  traceJobEdit,
  senstiveNameList,
  traceJobRun
} from '@/api/apisecurity/apitraceability/traceability'
import TraceabilityHistory from './traceabilityHistory'
import BaseList from '@/mixins/BaseList'

export default {
  name: 'traceability',
  mixins: [BaseList],
  watch: {},
  components: { TraceabilityHistory },
  data() {
    return {
      formData: null,
      ids: [],
      list: [],
      historyData: null,
      senstiveNameArr: [],
      TraceabilityHistoryDiv: false,
      showSearch: true,
      loading: false,
      buttonLoading: false,
      open: false,
      total: 0,

      applicationNameArr: [],
      senstiveTypeArr: [],
      title: '',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        applicationId: null,
        jobName: null,
        protocolName: null,
        sensitiveName: null,
        workId: null,
        status: null
      },
      form: {
        jobId: null,
        cronExpression: '0 0/30 * * * ?',
        applicationId: null,
        jobName: null,
        protocolName: null,
        sensitiveName: null,
        workId: null
      },
      rules: {
        jobName: [
          { required: true, message: '请输入任务名称', trigger: 'blur' }
        ],
        protocolName: [
          { required: true, message: '请选择协议', trigger: 'blur' }
        ],
        // applicationId: [
        //   { required: true, message: "请选择应用", trigger: "blur" },
        // ],
        workId: [
          { required: true, message: '请选择敏感字段类型', trigger: 'blur' }
        ],

        sensitiveName: [
          { required: true, message: '请选择敏感字段', trigger: 'blur' }
        ],

        cronExpression: [
          { required: true, message: '请输入执行周期', trigger: 'blur' },
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value.length) value = value.trim()
              let arr = value.split(' ')
              if (arr.length === 6 || arr.length === 7) {
                let [
                  seconds,
                  minutes,
                  hours,
                  dayOfMonth,
                  month,
                  dayOfWeek,
                  year
                ] = arr
                let notIn = arr.filter(
                    (item, index) =>
                        item !== '*' &&
                        item !== '?' &&
                        item !== undefined &&
                        item !== '' &&
                        index > 1
                )
                if (notIn.length > 0) {
                  callback()
                } else {
                  if (seconds === '*') {
                    callback(new Error('间隔时间必须大于15分钟'))
                  } else {
                    if (minutes === '*') {
                      callback(new Error('间隔时间必须大于15分钟'))
                    } else {
                      let minuteArr = minutes.split(',')
                      let illegal = minuteArr.filter((m) => {
                        if (m.includes('-')) {
                          return true
                        } else if (m.includes('/')) {
                          let [start, cycle] = m.split('/')
                          return cycle < 15
                        } else {
                          return m < 15
                        }
                      })
                      if (illegal.length) {
                        callback(new Error('间隔时间必须大于15分钟'))
                      } else {
                        callback()
                      }
                    }
                  }
                }
              } else {
                callback(new Error('请输入正确的corn表达式'))
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.promiseArr()
  },
  methods: {
    promiseArr() {
      Promise.all([
        this.applicationNameList(),
        this.senstiveTypeList(),
        this.getList()
      ]).then((res) => {
        this.list = res[2].rows.reduce((r, c) => {
          let applicationName = this.applicationNameId(c.applicationId)
          let senstiveTypeName = this.senstiveTypeNameId(c.workId)
          r.push({
            ...c,
            applicationName: applicationName,
            workName: senstiveTypeName
          })

          return r
        }, [])
      })
    },
    queryParamsChange(row) {
      this.queryParams.sensitiveName = null
      if (row && row !== null) {
        senstiveNameList({ workId: row }).then((res) => {
          if (res && res.code === 200) {
            this.senstiveNameArr = res.data
          } else {
            this.senstiveNameArr = []
          }
        })
      } else {
        this.senstiveNameArr = []
        this.queryParams.sensitiveName = null
      }
    },
    workIdChange(row) {
      this.form.sensitiveName = ''
      if (row && row !== null) {
        senstiveNameList({ workId: row }).then((res) => {
          if (res && res.code === 200) {
            this.senstiveNameArr = res.data
          } else {
            this.senstiveNameArr = []
          }
        })
      } else {
        this.senstiveNameArr = []
        this.form.sensitiveName = ''
      }
    },
    //应用名称
    applicationNameList() {
      return new Promise((resolve, reject) => {
        applicationNameList().then((res) => {
          if (res && res.code === 200) {
            this.applicationNameArr = res.data
            resolve(res)
          } else {
            this.applicationNameArr = []
            reject()
          }
        })
      })
    },
    //敏感字段
    senstiveTypeList() {
      return new Promise((resolve, reject) => {
        senstiveTypeList().then((res) => {
          if (res && res.code === 200) {
            this.senstiveTypeArr = res.data
            resolve(res)
          } else {
            this.senstiveTypeArr = []
            reject()
          }
        })
      })
    },
    //列表
    getList() {
      this.loading = true
      return new Promise((resolve, reject) => {
        traceJobList(this.queryParams)
            .then((res) => {
              if (res && res.code === 200) {
                resolve(res)
                this.loading = false
                this.total = res.total
              } else {
                this.list = []
                this.total = 0
                reject()
              }
            })
            .finally(() => {
              this.loading = false
            })
      })
    },
    //   查询
    handleQuery() {
      this.promiseArr()
    },
    // 提交
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.buttonLoading = true
          if (this.title === '编辑溯源管理') {
            traceJobEdit(this.form)
                .then((res) => {
                  if (res && res.code === 200) {
                    this.$GlobalSuccessMessage('编辑成功')
                    this.open = false
                    this.promiseArr()
                  } else {
                    this.$GlobalErrorConfirm('编辑失败', res.msg)
                  }
                })
                .finally(() => {
                  this.buttonLoading = false
                })
          } else {
            traceJobAdd(this.form)
                .then((res) => {
                  if (res && res.code === 200) {
                    this.$GlobalSuccessMessage('新增成功')
                    this.open = false
                    this.promiseArr()
                  } else {
                    this.$GlobalErrorConfirm('新增失败', res.msg)
                  }
                })
                .finally(() => {
                  this.buttonLoading = false
                })
          }
        }
      })
    },
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.jobId)
    },
    senstiveTypeNameId(id) {
      let al = this.senstiveTypeArr.find(
          (item) => parseInt(item.value) === parseInt(id)
      )
      return al ? al.name : ''
    },
    applicationNameId(id) {
      let al = this.applicationNameArr.find(
          (item) => parseInt(item.value) === parseInt(id)
      )
      return al ? al.name : ''
    },
    // 取消
    cancel() {
      this.open = false
    },
    // form表单重置
    reset() {
      this.form = {
        applicationId: null,
        jobName: null,
        protocolName: null,
        jobId: null,
        cronExpression: '0 0/30 * * * ?',
        sensitiveName: null,
        workId: null
      }
    },
    // 查询表单重置
    resetQuery() {
      this.queryParams = this.$options.data().queryParams;
    },
    // 新增
    handleAdd() {
      this.title = '新增溯源管理'
      this.open = true
      this.reset()
    },
    // 编辑
    handleEdit(data) {
      if (data && data.status === '0') {
        this.$GlobalErrorConfirm('编辑失败', '启用状态下不允许编辑')
        return
      }
      this.workIdChange(data.workId)
      this.title = '编辑溯源管理'
      this.open = true
      Reflect.ownKeys(this.form).forEach((k) => (this.form[k] = data[k]))
      this.form.applicationId = parseInt(this.form.applicationId)
      this.form.workId = parseInt(this.form.workId)
      let val = []
      this.applicationNameArr.forEach((item) => {
        val.push(item.value)
      })
      if (!val.includes(this.form.applicationId)) {
        this.form.applicationId = null
      }

      // this.form.applicationId = this.applicationNameArr.find(
      //   (item) => item.name === data.applicationId
      // )?.value;
      // this.form.workId = this.senstiveTypeArr.find(
      //   (item) => item.name === data.workId
      // )?.value;
    },
    // 删除
    handleDelete(data) {
      if (data && data.status === '0') {
        this.$GlobalErrorConfirm('删除失败', '启用状态下不允许删除')
        return
      }
      let ids = data.jobId || this.ids.join(',')
      this.$GlobalDeleteConfirm().then(() => {
        traceJobRemove({ ids: ids })
            .then((res) => {
              if (res && res.code == 200) {
                this.queryParams.pageNum = 1
                this.promiseArr()
                this.$GlobalSuccessMessage('删除成功')
              } else {
                this.$GlobalErrorConfirm('删除失败', res.msg)
              }
            })
      }).catch(()=>{});
    },
    // 立即执行
    immediateExecuteTask(row) {
      this.$GlobalDeleteConfirm('是否立即执行').then(() => {
        traceJobRun(row)
            .then((res) => {
              if (res && res.code == 200) {
                this.promiseArr()
                this.$GlobalSuccessMessage('操作成功')
              } else {
                this.$GlobalErrorConfirm('操作失败', res.msg)
              }
            })
      }).catch(()=>{});
    },
    // 执行历史
    taskHistoryFn(row) {
      console.log(row)
      this.historyData = row.jobName
      this.formData = row
      this.TraceabilityHistoryDiv = true
    },
    changeTraceabilityHistoryDiv() {
      this.TraceabilityHistoryDiv = false
    },

    // 启用停用
    handleStop(rows, row) {
      let status = row.status === '0' ? '1' : '0'
      let ids = row.jobId || this.ids.join(',')
      changeStatus({
        jobId: ids,
        status: status
      })
          .then((res) => {
            if (res && res.code === 200) {
              this.$GlobalSuccessMessage('操作成功')
              this.promiseArr()
            } else {
              this.$GlobalErrorConfirm('操作失败', res.msg)
            }
          })
    },
    setCommand(command, row) {
      return {
        command: command ? command : null,
        data: row ? row : null
      }
    },
    handleCommand(command) {
      if (command.command === 'edit') {
        this.handleEdit(command.data)
      } else if (command.command === 'change') {
        this.handleStop(null, command.data)
      } else if (command.command === 'delete') {
        this.handleDelete(command.data)
      }
    }
  }
}
</script>

<style scoped lang="scss">
</style>

